<!DOCTYPE html>
<html lang="en">
<head>
  <meta charset="utf-8">
<!-- threads.qdoc -->
  <title>Multithreading Technologies in Qt | Qt 5.14</title>
  <link rel="stylesheet" type="text/css" href="style/offline-simple.css" />
  <script type="text/javascript">
    document.getElementsByTagName("link").item(0).setAttribute("href", "style/offline.css");
    // loading style sheet breaks anchors that were jumped to before
    // so force jumping to anchor again
    setTimeout(function() {
        var anchor = location.hash;
        // need to jump to different anchor first (e.g. none)
        location.hash = "#";
        setTimeout(function() {
            location.hash = anchor;
        }, 0);
    }, 0);
  </script>
</head>
<body>
<div class="header" id="qtdocheader">
  <div class="main">
    <div class="main-rounded">
      <div class="navigationbar">
        <table><tr>
<td ><a href="index.html">Qt 5.14</a></td><td >Multithreading Technologies in Qt</td></tr></table><table class="buildversion"><tr>
<td id="buildversion" width="100%" align="right">Qt 5.14.2 Reference Documentation</td>
        </tr></table>
      </div>
    </div>
<div class="content">
<div class="line">
<div class="content mainContent">
  <link rel="prev" href="threads.html" />
  <link rel="next" href="threads-synchronizing.html" />
<p class="naviNextPrevious headerNavi">
<a class="prevPage" href="threads.html">Thread Support in Qt</a>
<span class="naviSeparator">  &#9702;  </span>
<a class="nextPage" href="threads-synchronizing.html">Synchronizing Threads</a>
</p><p/>
<div class="sidebar">
<div class="toc">
<h3><a name="toc">Contents</a></h3>
<ul>
<li class="level1"><a href="#qthread-low-level-api-with-optional-event-loops">QThread: Low-Level API with Optional Event Loops</a></li>
<li class="level1"><a href="#qthreadpool-and-qrunnable-reusing-threads">QThreadPool and QRunnable: Reusing Threads</a></li>
<li class="level1"><a href="#qt-concurrent-using-a-high-level-api">Qt Concurrent: Using a High-level API</a></li>
<li class="level1"><a href="#workerscript-threading-in-qml">WorkerScript: Threading in QML</a></li>
<li class="level1"><a href="#choosing-an-appropriate-approach">Choosing an Appropriate Approach</a></li>
<li class="level2"><a href="#comparison-of-solutions">Comparison of Solutions</a></li>
<li class="level2"><a href="#example-use-cases">Example Use Cases</a></li>
</ul>
</div>
<div class="sidebar-content" id="sidebar-content"></div></div>
<h1 class="title">Multithreading Technologies in Qt</h1>
<span class="subtitle"></span>
<!-- $$$threads-technologies.html-description -->
<div class="descr"> <a name="details"></a>
<p>Qt offers many classes and functions for working with threads. Below are four different approaches that Qt programmers can use to implement multithreaded applications.</p>
<a name="qthread-low-level-api-with-optional-event-loops"></a>
<h2 id="qthread-low-level-api-with-optional-event-loops">QThread: Low-Level API with Optional Event Loops</h2>
<p><a href="../qtcore/qthread.html">QThread</a> is the foundation of all thread control in Qt. Each <a href="../qtcore/qthread.html">QThread</a> instance represents and controls one thread.</p>
<p><a href="../qtcore/qthread.html">QThread</a> can either be instantiated directly or subclassed. Instantiating a <a href="../qtcore/qthread.html">QThread</a> provides a parallel event loop, allowing <a href="../qtcore/qobject.html">QObject</a> slots to be invoked in a secondary thread. Subclassing a <a href="../qtcore/qthread.html">QThread</a> allows the application to initialize the new thread before starting its event loop, or to run parallel code without an event loop.</p>
<p>See the <a href="../qtcore/qthread.html">QThread class reference</a> and the <a href="examples-threadandconcurrent.html">threading examples</a> for demonstrations on how to use <a href="../qtcore/qthread.html">QThread</a>.</p>
<a name="qthreadpool-and-qrunnable-reusing-threads"></a>
<h2 id="qthreadpool-and-qrunnable-reusing-threads">QThreadPool and QRunnable: Reusing Threads</h2>
<p>Creating and destroying threads frequently can be expensive. To reduce this overhead, existing threads can be reused for new tasks. <a href="../qtcore/qthreadpool.html">QThreadPool</a> is a collection of reuseable QThreads.</p>
<p>To run code in one of a <a href="../qtcore/qthreadpool.html">QThreadPool</a>'s threads, reimplement <a href="../qtcore/qrunnable.html#run">QRunnable::run</a>() and instantiate the subclassed <a href="../qtcore/qrunnable.html">QRunnable</a>. Use <a href="../qtcore/qthreadpool.html#start">QThreadPool::start</a>() to put the <a href="../qtcore/qrunnable.html">QRunnable</a> in the <a href="../qtcore/qthreadpool.html">QThreadPool</a>'s run queue. When a thread becomes available, the code within <a href="../qtcore/qrunnable.html#run">QRunnable::run</a>() will execute in that thread.</p>
<p>Each Qt application has a global thread pool, which is accessible through <a href="../qtcore/qthreadpool.html#globalInstance">QThreadPool::globalInstance</a>(). This global thread pool automatically maintains an optimal number of threads based on the number of cores in the CPU. However, a separate <a href="../qtcore/qthreadpool.html">QThreadPool</a> can be created and managed explicitly.</p>
<a name="qt-concurrent-using-a-high-level-api"></a>
<h2 id="qt-concurrent-using-a-high-level-api">Qt Concurrent: Using a High-level API</h2>
<p>The <a href="../qtconcurrent/qtconcurrent-index.html">Qt Concurrent</a> module provides high-level functions that deal with some common parallel computation patterns: map, filter, and reduce. Unlike using <a href="../qtcore/qthread.html">QThread</a> and <a href="../qtcore/qrunnable.html">QRunnable</a>, these functions never require the use of <a href="threads-synchronizing.html#low-level-synchronization-primitives">low-level threading primitives</a> such as mutexes or semaphores. Instead, they return a <a href="../qtcore/qfuture.html">QFuture</a> object which can be used to retrieve the functions' results when they are ready. <a href="../qtcore/qfuture.html">QFuture</a> can also be used to query computation progress and to pause/resume/cancel the computation. For convenience, <a href="../qtcore/qfuturewatcher.html">QFutureWatcher</a> enables interactions with <a href="../qtcore/qfuture.html">QFuture</a>s via signals and slots.</p>
<p><a href="../qtconcurrent/qtconcurrent-index.html">Qt Concurrent</a>'s map, filter and reduce algorithms automatically distribute computation across all available processor cores, so applications written today will continue to scale when deployed later on a system with more cores.</p>
<p>This module also provides the <a href="../qtconcurrent/qtconcurrent.html#run">QtConcurrent::run</a>() function, which can run any function in another thread. However, <a href="../qtconcurrent/qtconcurrent.html#run">QtConcurrent::run</a>() only supports a subset of features available to the map, filter and reduce functions. The <a href="../qtcore/qfuture.html">QFuture</a> can be used to retrieve the function's return value and to check if the thread is running. However, a call to <a href="../qtconcurrent/qtconcurrent.html#run">QtConcurrent::run</a>() uses one thread only, cannot be paused/resumed/canceled, and cannot be queried for progress.</p>
<p>See the <a href="../qtconcurrent/qtconcurrent-index.html">Qt Concurrent</a> module documentation for details on the individual functions.</p>
<a name="workerscript-threading-in-qml"></a>
<h2 id="workerscript-threading-in-qml">WorkerScript: Threading in QML</h2>
<p>The <a href="../qtqmlworkerscript/qml-qtqml-workerscript-workerscript.html">WorkerScript</a> QML type lets JavaScript code run in parallel with the GUI thread.</p>
<p>Each <a href="../qtqmlworkerscript/qml-qtqml-workerscript-workerscript.html">WorkerScript</a> instance can have one <code>.js</code> script attached to it. When <a href="../qtqmlworkerscript/qml-qtqml-workerscript-workerscript.html#sendMessage-method">WorkerScript.sendMessage</a>() is called, the script will run in a separate thread (and a separate <a href="../qtqml/qqmlcontext.html">QML context</a>). When the script finishes running, it can send a reply back to the GUI thread which will invoke the <a href="../qtqmlworkerscript/qml-qtqml-workerscript-workerscript.html#message-signal">WorkerScript.onMessage</a>() signal handler.</p>
<p>Using a <a href="../qtqmlworkerscript/qml-qtqml-workerscript-workerscript.html">WorkerScript</a> is similar to using a worker <a href="../qtcore/qobject.html">QObject</a> that has been moved to another thread. Data is transferred between threads via signals.</p>
<p>See the <a href="../qtqmlworkerscript/qml-qtqml-workerscript-workerscript.html">WorkerScript</a> documentation for details on how to implement the script, and for a list of data types that can be passed between threads.</p>
<a name="choosing-an-appropriate-approach"></a>
<h2 id="choosing-an-appropriate-approach">Choosing an Appropriate Approach</h2>
<p>As demonstrated above, Qt provides different solutions for developing threaded applications. The right solution for a given application depends on the purpose of the new thread and the thread's lifetime. Below is a comparison of Qt's threading technologies, followed by recommended solutions for some example use cases.</p>
<a name="comparison-of-solutions"></a>
<h3 id="comparison-of-solutions">Comparison of Solutions</h3>
<div class="table"><table class="generic">
 <thead><tr class="qt-style"><th >Feature</th><th ><a href="../qtcore/qthread.html">QThread</a></th><th ><a href="../qtcore/qrunnable.html">QRunnable</a> and <a href="../qtcore/qthreadpool.html">QThreadPool</a></th><th ><a href="../qtconcurrent/qtconcurrent.html#run">QtConcurrent::run</a>()</th><th >Qt Concurrent (Map, Filter, Reduce)</th><th ><a href="../qtqmlworkerscript/qml-qtqml-workerscript-workerscript.html">WorkerScript</a></th></tr></thead>
<tr valign="top" class="odd"><td >Language</td><td >C++</td><td >C++</td><td >C++</td><td >C++</td><td >QML</td></tr>
<tr valign="top" class="even"><td >Thread priority can be specified</td><td >Yes</td><td >Yes</td><td ></td><td ></td><td ></td></tr>
<tr valign="top" class="odd"><td >Thread can run an event loop</td><td >Yes</td><td ></td><td ></td><td ></td><td ></td></tr>
<tr valign="top" class="even"><td >Thread can receive data updates through signals</td><td >Yes (received by a worker <a href="../qtcore/qobject.html">QObject</a>)</td><td ></td><td ></td><td ></td><td >Yes (received by <a href="../qtqmlworkerscript/qml-qtqml-workerscript-workerscript.html">WorkerScript</a>)</td></tr>
<tr valign="top" class="odd"><td >Thread can be controlled using signals</td><td >Yes (received by <a href="../qtcore/qthread.html">QThread</a>)</td><td ></td><td ></td><td >Yes (received by <a href="../qtcore/qfuturewatcher.html">QFutureWatcher</a>)</td><td ></td></tr>
<tr valign="top" class="even"><td >Thread can be monitored through a <a href="../qtcore/qfuture.html">QFuture</a></td><td ></td><td ></td><td >Partially</td><td >Yes</td><td ></td></tr>
<tr valign="top" class="odd"><td >Built-in ability to pause/resume/cancel</td><td ></td><td ></td><td ></td><td >Yes</td><td ></td></tr>
</table></div>
<a name="example-use-cases"></a>
<h3 id="example-use-cases">Example Use Cases</h3>
<div class="table"><table class="generic">
 <thead><tr class="qt-style"><th >Lifetime of thread</th><th >Operation</th><th >Solution</th></tr></thead>
<tr valign="top" class="odd"><td >One call</td><td >Run a new linear function within another thread, optionally with progress updates during the run.</td><td >Qt provides different solutions:<ul>
<li>Place the function in a reimplementation of <a href="../qtcore/qthread.html#run">QThread::run</a>() and start the <a href="../qtcore/qthread.html">QThread</a>. Emit signals to update progress. OR</li>
<li>Place the function in a reimplementation of <a href="../qtcore/qrunnable.html#run">QRunnable::run</a>() and add the <a href="../qtcore/qrunnable.html">QRunnable</a> to a <a href="../qtcore/qthreadpool.html">QThreadPool</a>. Write to a <a href="threads-synchronizing.html">thread-safe variable</a> to update progress. OR</li>
<li>Run the function using <a href="../qtconcurrent/qtconcurrent.html#run">QtConcurrent::run</a>(). Write to a <a href="threads-synchronizing.html">thread-safe variable</a> to update progress.</li>
</ul>
</td></tr>
<tr valign="top" class="even"><td >One call</td><td >Run an existing function within another thread and get its return value.</td><td >Run the function using <a href="../qtconcurrent/qtconcurrent.html#run">QtConcurrent::run</a>(). Have a <a href="../qtcore/qfuturewatcher.html">QFutureWatcher</a> emit the <a href="../qtcore/qfuturewatcher.html#finished">finished()</a> signal when the function has returned, and call <a href="../qtcore/qfuturewatcher.html#result">QFutureWatcher::result</a>() to get the function's return value.</td></tr>
<tr valign="top" class="odd"><td >One call</td><td >Perform an operation on all items of a container, using all available cores. For example, producing thumbnails from a list of images.</td><td >Use Qt Concurrent's <a href="../qtconcurrent/qtconcurrent.html#filter">QtConcurrent::filter</a>() function to select container elements, and the <a href="../qtconcurrent/qtconcurrent.html#map">QtConcurrent::map</a>() function to apply an operation to each element. To fold the output into a single result, use <a href="../qtconcurrent/qtconcurrent.html#filteredReduced">QtConcurrent::filteredReduced</a>() and <a href="../qtconcurrent/qtconcurrent.html#mappedReduced">QtConcurrent::mappedReduced</a>() instead.</td></tr>
<tr valign="top" class="even"><td >One call/Permanent</td><td >Perfrom a long computation in a pure QML application, and update the GUI when the results are ready.</td><td >Place the computation code in a <code>.js</code> script and attach it to a <a href="../qtqmlworkerscript/qml-qtqml-workerscript-workerscript.html">WorkerScript</a> instance. Call <a href="../qtqmlworkerscript/qml-qtqml-workerscript-workerscript.html#sendMessage-method">WorkerScript.sendMessage</a>() to start the computation in a new thread. Let the script call sendMessage() too, to pass the result back to the GUI thread. Handle the result in <code>onMessage</code> and update the GUI there.</td></tr>
<tr valign="top" class="odd"><td >Permanent</td><td >Have an object living in another thread that can perform different tasks upon request and/or can receive new data to work with.</td><td >Subclass a <a href="../qtcore/qobject.html">QObject</a> to create a worker. Instantiate this worker object and a <a href="../qtcore/qthread.html">QThread</a>. Move the worker to the new thread. Send commands or data to the worker object over queued signal-slot connections.</td></tr>
<tr valign="top" class="even"><td >Permanent</td><td >Repeatedly perform an expensive operation in another thread, where the thread does not need to receive any signals or events.</td><td >Write the infinite loop directly within a reimplementation of <a href="../qtcore/qthread.html#run">QThread::run</a>(). Start the thread without an event loop. Let the thread emit signals to send data back to the GUI thread.</td></tr>
</table></div>
</div>
<!-- @@@threads-technologies.html -->
<p class="naviNextPrevious footerNavi">
<a class="prevPage" href="threads.html">Thread Support in Qt</a>
<span class="naviSeparator">  &#9702;  </span>
<a class="nextPage" href="threads-synchronizing.html">Synchronizing Threads</a>
</p>
        </div>
       </div>
   </div>
   </div>
</div>
<div class="footer">
   <p>
   <acronym title="Copyright">&copy;</acronym> 2020 The Qt Company Ltd.
   Documentation contributions included herein are the copyrights of
   their respective owners.<br/>    The documentation provided herein is licensed under the terms of the    <a href="http://www.gnu.org/licenses/fdl.html">GNU Free Documentation    License version 1.3</a> as published by the Free Software Foundation.<br/>    Qt and respective logos are trademarks of The Qt Company Ltd.     in Finland and/or other countries worldwide. All other trademarks are property
   of their respective owners. </p>
</div>
</body>
</html>
